package com.eastdigit.shiro.filter;

import com.eastdigit.servlet.ReqBean;
import com.eastdigit.shiro.ShiroConstants;
import com.eastdigit.shiro.authc.StateToken;
import com.eastdigit.shiro.authc.StatelessToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class StatelessAuthcFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException,
            ServletException {
        String url = ((HttpServletRequest) request).getServletPath();
        ReqBean reqBean = (ReqBean) request.getAttribute(ReqBean.NAME);
        reqBean.setStateless(true);

        AuthenticationToken token;
        if (url.contains(getLoginUrl())) {// 登录交给有状态来处理
            String username = reqBean.getInfo("userCode");
            String password = reqBean.getInfo("password");
            token = new StateToken(username, password == null ? null : password.toCharArray(), false, "", null);
        } else {
            token = new StatelessToken(reqBean.getUserId(), reqBean.getTimestamp(), reqBean.getNonce(),
                    reqBean.getClientDigest());
        }
        try {
            getSubject(request, response).login(token);
        } catch (Exception e) {
            RequestDispatcher rd = request.getRequestDispatcher(getLoginUrl());
            rd.forward(request, response);
        }
        return true;
    }

    @Override
    protected void executeChain(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception {
        String url = ((HttpServletRequest) request).getServletPath();
        if (url.startsWith(ShiroConstants.PREFIX_STATELESS)) {// 手机端无状态登录
            RequestDispatcher rd = request
                    .getRequestDispatcher(url.substring(ShiroConstants.PREFIX_STATELESS.length() - 1));
            rd.forward(request, response);// 转发到具体action
        } else {
            super.executeChain(request, response, chain);
        }
    }
}
